var fs = require('fs');
//var napa = require("napajs");
var minify = require("minify-images");
var imgHash = require('./imghash1.js');

function compress(cname, imgs, sig, hashPath, minPath) {
	var imgName = imgs[sig];
	if (sig >= imgs.length) {
		console.log("=====Compression Complete!=====");
		console.log("=====Generating image finger prints=====");
		return runHash(cname, imgs, 0, hashPath);
	}
	minify.compress({
		src: '../images/' + cname + '/' + imgName,
		dest: minPath + "/" + cname,
		jpg: {
			quality: '20'
		},
		png: {
			quality: '50'
		}
	}).then(files => {
		sig++;
		console.log("compressed>>>>>>>>" + imgName);
		compress(cname, imgs, sig, hashPath, minPath);
	}).catch(error => {
		throw error;
	});
}

function runHash(cname, imgs, sig, path) {
	console.log(cname + "=============" + sig);
	var hashPath = path;
	var imgArr = imgs;
	var obj = {};
	for(var i = 0; i < imgArr.length; i++) {
		if(!obj.hasOwnProperty(imgArr[i])) {
			var imgUrl = "../images/" + cname + "/" + imgArr[i];
			var hash2 = imgHash.hash(imgUrl);
			obj[imgArr[i]] = hash2;
			console.log(imgArr[i] + "------>>>>>>>>>>" + hash2);
		}
	}
	var t = JSON.stringify(obj);
	console.log(cname + "----->>>>>>>> Wrting...");
	var reg = /.*[\u4e00-\u9fa5]+.*$/;
	var hasChinese = reg.test(cname);
	var encode = 'utf-8';
	if (hasChinese) {
		cname = encodeURIComponent(cname);
		console.log("编码后--------" + cname);
		console.log("解码后--------" + decodeURIComponent(cname));
	};
	fs.writeFileSync(hashPath + "/" + cname + ".json", t);
	console.log(cname + "----->>>>>>>> Wrting Completed!...");
	
}

module.exports = {
	compress,
	runHash
}
